package com.hzit.servlet;

import cn.hutool.core.util.StrUtil;
import com.hzit.entity.R;
import com.hzit.entity.Student;
import com.hzit.service.IStudentService;
import com.hzit.util.ResponseUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private IStudentService studentService;
	@Override
	public void init() throws ServletException {
		//1. 得到spring容器
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		//2. 在spring容器中得到IStudentService对象
		studentService = wac.getBean(IStudentService.class);
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf8");
		String cmd = req.getParameter("cmd");
		if(StrUtil.isNotBlank(cmd)){
			if("list".equals(cmd)){     // 得到学生列表
				list(req,resp);
			}
		}
		// http://localhost:9000/student?cmd=list
	}
	//2. 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1. 得到学生列表
		List<Student> studentList = studentService.findAll();       // 从模型层取得数据
		R<List<Student>> ok = R.ok(studentList);
		//2. 将r对象响应到前端
		ResponseUtil.out(resp,ok);                                  // 将数据送到视图层展示
	}
}
